package dxlateplate;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SubmitLatePlateServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(SubmitLatePlateServlet.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        String userName = "";

        if(user != null) {
            userName = user.getEmail();
        } else {
            userName = req.getParameter("userName");
        }

        String name = req.getParameter("name");
        String day = req.getParameter("day");
        int type = Integer.parseInt(req.getParameter("type"));
        String comments = req.getParameter("comments");
        String perm = req.getParameter("permanent");
        boolean permanent = false;
        if(perm != null && perm.equalsIgnoreCase("on")) {
        	permanent = true;
        }
        
        
        if (comments.equalsIgnoreCase("enter comments here")) {
            comments = "";
        }

        Date date = new Date();
        int rDay = date.getDay();
        int rHour = date.getHours();
        //daylight savings
        if (rHour < 5) {
        	rHour = rHour + 19;
        	rDay = rDay - 1;
        } else if (rHour >= 5 ) {
        	rHour = rHour - 5;
        }
        int rMinute = date.getMinutes();
        
        
        LatePlate latePlate = new LatePlate(userName, name, day, type, comments, rHour, rMinute, rDay, permanent);
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(latePlate);
        } finally {
            pm.close();
        }

        resp.sendRedirect("/latePlateHome.jsp");
    }
}
